/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-12-07     zqyh       the first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

//#include "drv_spi.h"
#include "drv_qspi.h"
#include "spi_flash_sfud.h"


#include <fal.h>
#include "dfs_fs.h"
//#include <dfs_posix.h>


#define QSPI_BUS_NAME                   "qspi1"
#define QSPI_DEVICE_NAME                "qspi10"
#define QSPI_FLASH_NAME                 "norflash0"
#define QSPI_CS_PIN                     GET_PIN(B, 6)   //此处注意引脚区分，用你自己的


/* 定义要使用的分区名字 */
#define ROOT_PATH                       "/"
#define FLASH_PARTITION_NAME            "flash0"
#define FLASH_FS_TYPE                   "lfs"


int rt_hw_qspi_flash_with_sfud_init(void)
{
    if (stm32_qspi_bus_attach_device(QSPI_BUS_NAME, QSPI_DEVICE_NAME, (rt_uint32_t)QSPI_CS_PIN, 4, RT_NULL, RT_NULL) != RT_EOK)
        return -RT_ERROR;

#ifdef  RT_USING_SFUD
    if (rt_sfud_flash_probe(QSPI_FLASH_NAME, QSPI_DEVICE_NAME) == RT_NULL)
        return -RT_ERROR;
#endif

    return RT_EOK;
}


int rt_qspi_flash_littlefs_mount(void)
{
    struct rt_device *mtd_dev = RT_NULL;

    /*初始化FAL*/
    if (fal_init() < 0)
    {
        LOG_E("fal_init,fault!");
        return -RT_ERROR;
    }

    /* QSPI FLASH 生成 mtd 设备 */
    mtd_dev = fal_mtd_nor_device_create(FLASH_PARTITION_NAME);
    if (!mtd_dev)
    {
        LOG_E("Can't create a mtd device on '%s' partition.", FLASH_PARTITION_NAME);
        return -RT_ERROR;
    }
    else
    {
        /* 挂载 littlefs */
        if (dfs_mount(FLASH_PARTITION_NAME, ROOT_PATH, FLASH_FS_TYPE, 0, 0) == 0) {
            LOG_I("mount '%s' to '%s' success,file system:%s", FLASH_PARTITION_NAME, ROOT_PATH, FLASH_FS_TYPE);
        } else {
            LOG_E("Failed mount '%s' to '%s'!", FLASH_PARTITION_NAME, ROOT_PATH);
            /* 格式化文件系统 */
            dfs_mkfs("lfs", FLASH_PARTITION_NAME);
            return -RT_ERROR;
        }
    }

    return 0;
}


int rt_qspi_init_then_mount(void)
{
    rt_hw_qspi_flash_with_sfud_init();
    rt_thread_mdelay(10);
    rt_qspi_flash_littlefs_mount();
}

INIT_COMPONENT_EXPORT(rt_qspi_init_then_mount);

